{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Test PyTorch MNIST Model via OAuth Gateway\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python Dependencies\n",
    "\n",
    " * Requests\n",
    " * Numpy\n",
    " * Matplotlib\n",
    " * Tensorflow"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Set up REST and gRPC methods"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Install gRPC modules for the prediction protos."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "from requests.auth import HTTPBasicAuth\n",
    "from random import randint,random\n",
    "import numpy as np\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "from matplotlib import pyplot as plt\n",
    "import json\n",
    "\n",
    "OAUTH_API=\"localhost:8003\"\n",
    "\n",
    "def rest_request(deploymentName,request):\n",
    "    response = requests.post(\n",
    "                \"http://\"+OAUTH_API+\"/seldon/\"+deploymentName+\"/api/v0.1/predictions\",\n",
    "                json=request)\n",
    "    return response.json() \n",
    "\n",
    "def get_token():\n",
    "    payload = {'grant_type': 'client_credentials'}\n",
    "    response = requests.post(\n",
    "                \"http://\"+OAUTH_API+\"/oauth/token\",\n",
    "                auth=HTTPBasicAuth('oauth-key-pymnist', 'oauth-secret'),\n",
    "                data=payload)\n",
    "    token =  response.json()[\"access_token\"]\n",
    "    return token\n",
    "\n",
    "def rest_request(request,token):\n",
    "    headers = {'Authorization': 'Bearer '+token}\n",
    "    response = requests.post(\n",
    "                \"http://\"+OAUTH_API+\"/api/v0.1/predictions\",\n",
    "                headers=headers,\n",
    "                json=request)\n",
    "    return response.json()\n",
    "    \n",
    "def gen_image(arr):\n",
    "    two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)\n",
    "    plt.imshow(two_d,cmap=plt.cm.gray_r, interpolation='nearest')\n",
    "    return plt\n",
    "\n",
    "def download_mnist():\n",
    "    return input_data.read_data_sets(\"MNIST_data/\", one_hot = True)\n",
    "\n",
    "def predict_rest_mnist(mnist):\n",
    "    token = get_token()\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(1)\n",
    "    chosen=0\n",
    "    gen_image(batch_xs[chosen]).show()\n",
    "    data = batch_xs[chosen].reshape((1,784))\n",
    "    features = [\"X\"+str(i+1) for i in range (0,784)]\n",
    "    request = {\"data\":{\"names\":features,\"ndarray\":data.tolist()}}\n",
    "    predictions = rest_request(request,token)\n",
    "    fpreds = [ '%.2f' % elem for elem in predictions[\"data\"][\"ndarray\"][0] ]\n",
    "    m = dict(zip(predictions[\"data\"][\"names\"],fpreds))\n",
    "    print(json.dumps(m,indent=2))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Ensure you have port forwarded to the Seldon API OAUTH Gateway pod:**\n",
    "\n",
    "```\n",
    "kubectl port-forward $(kubectl get pods -n default -l app=seldon-apiserver-container-app -o jsonpath='{.items[0].metadata.name}') -n default 8003:8080\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mnist = download_mnist()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predict_rest_mnist(mnist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
